//
//  IAAAuthCheckVC.m
//  iPadAuditAuthorise
//
//  Created by XiangDongMBP on 16/9/2.
//  Copyright © 2016年 XiangDong. All rights reserved.
//

#import "IAAAuthCheckVC.h"
#import "IAAAuthCheckTHeader.h"
#import "IAAAuthCheckTCell.h"
#import "IAADetailRootVC.h"
#import <MJRefresh.h>
#import "IAAAuthCheckModel.h"
#import <UIScrollView+EmptyDataSet.h>
#import "NSTimer+XDTimer.h"

@interface IAAAuthCheckVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IAAAuthCheckModel *model;
@property (strong, nonatomic) NSDate *lastReqTime;
@property (strong, nonatomic) NSTimer *timer;

@end

static NSTimeInterval const kTimerInterval = 5; //!< 每次间隔5s刷新一次界面
static NSInteger const kPageSize = 15;          //!< 每次请求的记录数
static NSString * const reuseHeaderId = @"IAAAuthCheckTCell";
static NSString * const reuseCellId = @"IAAAuthCheckTCell";

@implementation IAAAuthCheckVC

- (void)dealloc {
    [self removeRefreshNotification];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // 注册通知
    [self addRefreshNotification];
    // 逻辑数据
    [self initLogicData];
    //设置导航栏
    [self initNavigationBar];
    //設置子Views
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self startTimer];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self stopTimer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)addRefreshNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerToRefresh) name:IAA_NOTI_AUCH_REFRESH object:nil];
}

- (void)removeRefreshNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:IAA_NOTI_AUCH_REFRESH object:nil];
}

- (void)initLogicData {
    self.lastReqTime = [NSDate date];
}

- (void)startTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:kTimerInterval block:^(NSTimeInterval time) {
        [weakSelf tableViewRefresh:weakSelf.tableView.mj_header];
    } repeats:YES];
    [self.timer fire];  //立刻请求
}

- (void)stopTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)initNavigationBar {
    self.navigationItem.title = @"业务审核";
}

- (void)initSubViews {
    [self.tableView registerClass:[IAAAuthCheckTHeader class] forHeaderFooterViewReuseIdentifier:reuseHeaderId];
    UINib *cellNib = [UINib nibWithNibName:reuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:reuseCellId];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    //下拉、上拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    
    // 触发刷新
    [self triggerToRefresh];
}

- (void)triggerToRefresh {
    [self.tableView.mj_header beginRefreshing];
}

- (void)refreshWholeView {
    if (self.model.taskList.count >= self.model.totalCout) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    [self.tableView reloadData];
}

#pragma mark - <UITableViewDelegate>代理
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    
    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    IAAAuthCheckTHeader *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:reuseHeaderId];
    NSArray<NSString *> *array = @[@"任务流水号", @"终端号", @"网点号", @"交易名称", @"申请时间", @"任务级别", @"任务状态"];
    [view configViewWithArrar:array];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    IAAAuthCheckTaskItem *item = self.model.taskList[indexPath.row];
    [self requestAuthCheckDetail:item];
}

#pragma mark - <UITableViewDataSource>代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.taskList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IAAAuthCheckTCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseCellId forIndexPath:indexPath];
    if (indexPath.row < self.model.taskList.count) {
        [cell configViewWithData:self.model.taskList[indexPath.row]];
    }
    return cell;
}

#pragma mark - <DZNEmptyDataSetSource>代理
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"Glo_load_sad"];
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"无数据"];
}

#pragma mark - <DZNEmptyDataSetDelegate>代理
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - 网络请求
// 请求业务审核的列表
- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    
    NSDate *curDate = [NSDate date];
    if ([curDate timeIntervalSinceDate:self.lastReqTime] > 2*60*60) {   //超过2小时未请求，做登出处理
        [self tableViewEndRefresh:isHeader];
        MBProgressHUD *hud = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"会话超时"];
        hud.completionBlock = ^(){
            [self requestlogut];
        };
    } else {
        self.lastReqTime = curDate;
    }
    
    NSInteger startIndex = isHeader ? 0 : self.model.taskList.count;
    NSString *urlStr = [IAAUrlProtocolMerge appAuthCheckTaskList];
    NSDictionary *pars = @{@"orgNo"  : IAA_APP_DELEGATE.organizeId,
                           @"token" : IAA_APP_DELEGATE.token,
                           @"userNo" : IAA_APP_DELEGATE.userNo,
                           @"osName": @"iOS",
                           @"startIndex" : @(startIndex),
                           @"pageSize": @(kPageSize)};
    
    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"业务审核返回 %@", responseObject);
        [self tableViewEndRefresh:isHeader];
        IAAAuthCheckModel *temp = [IAAAuthCheckModel yy_modelWithJSON:responseObject];
        // 0006代表柜员已签退，调用签退接口，返回登录界面
        if ([temp.resultCode isEqualToString:@"0006"]) {
            MBProgressHUD *hud = [MBProgressHUD showPromptWithAutoHideInView:self.view message:temp.resultMsg];
            hud.completionBlock = ^(){
                [self requestlogut];
            };
        } else {
            if (isHeader || !self.model) {
                self.model = temp;
            } else {
                [self.model addMoreWithData:temp];
            }
            [self refreshWholeView];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"业务审核失败 %@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

//请求业务审核详情
- (void)requestAuthCheckDetail:(IAAAuthCheckTaskItem *)taskItem {
    NSString *urlStr = [IAAUrlProtocolMerge appAuthCheckTaskDetail];
    NSDictionary *pars = @{@"orgNo"  : IAA_APP_DELEGATE.organizeId,
                           @"userNo" : IAA_APP_DELEGATE.userNo,
                           @"token"  : IAA_APP_DELEGATE.token,
                           @"osName" : @"iOS",
                           @"busiId" : taskItem.busiId,
                           @"taskId" : @(taskItem.taskId)};
    
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"业务审核详情返回%@", responseObject);
        [hud hide:NO];
        IAAAuthCheckDetailModel *model = [IAAAuthCheckDetailModel yy_modelWithJSON:responseObject];
        if ([model.resultCode isEqualToString:IAA_RESULT_CODE_SUC]) {
            [self jumpToDetailRootVC:taskItem model:model];
        }else{
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:model.resultMsg];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"业务审核详情失败%@", error);
        [hud hide:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)jumpToDetailRootVC:(IAAAuthCheckTaskItem *)item model:(IAAAuthCheckDetailModel *)model {
    IAADetailRootVC *vc = [[IAADetailRootVC alloc] init];
    vc.taskItem = item;
    vc.authDetailModel = model;
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:navVC animated:YES completion:nil];
}

// 请求登出处理
- (void)requestlogut {
    NSString *urlStr = [IAAUrlProtocolMerge appLoginOutAction];
    
    NSDictionary *pars = @{@"organizeId"  : IAA_APP_DELEGATE.organizeId,
                           @"uname" : IAA_APP_DELEGATE.userNo,
                           @"token" : IAA_APP_DELEGATE.token,
                           @"osName": @"iOS"};
    
    // 顯示等待圈圈
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"登出请求返回%@", responseObject);
        [hud hide:NO];
        if ([responseObject[@"resultCode"] isEqualToString:IAA_RESULT_CODE_SUC] ||
            [responseObject[@"resultCode"] isEqualToString:@"0007"]) {
            [self jumpToLoginVC];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[@"resultMsg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hide:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)jumpToLoginVC {
    UIStoryboard *mainSB = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController * vc = [mainSB instantiateViewControllerWithIdentifier:@"IAALoginVC"];
    [UIApplication sharedApplication].keyWindow.rootViewController = vc;
    //转场动画
    CATransition *anim = [CATransition animation];
    //    anim.type = @"rippleEffect";
    anim.duration = 0.3;
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
}

@end
